//
//  ZDSelectPayController.m
//  特种车调度
//
//  Created by 陈宇 on 15/8/22.
//
//

#import "ZDSelectPayController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "DataSigner.h"
#import "ZDPayResultController.h"
#import "BMAccountManager.h"
#import "UPPayPlugin.h"
#import "UPPayPluginDelegate.h"
#import "ZDWalletController.h"

@interface ZDSelectPayController () <UPPayPluginDelegate>

@property (weak, nonatomic) IBOutlet UITextField *priceTextfield;
@property (weak, nonatomic) IBOutlet UIButton *alipayButton;
@property (weak, nonatomic) IBOutlet UIButton *yinlianButtob;

@property (nonatomic, assign) NSInteger selectIndex;

- (IBAction)selctPayAction:(UITapGestureRecognizer *)recognizer;
- (IBAction)goPayAction:(id)sender;

@end

@implementation ZDSelectPayController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem.target = self;
    _selectIndex = NSNotFound;
}

- (void)back
{
    if (_type == 1) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)selctPayAction:(UITapGestureRecognizer *)recognizer
{
    _alipayButton.selected = _yinlianButtob.selected = NO;
    _selectIndex = recognizer.view.tag;
    if (_selectIndex) {
        _yinlianButtob.selected = YES;
    } else {
        _alipayButton.selected = YES;
    }
}

- (IBAction)goPayAction:(id)sender {
    
    NSScanner *scanner = [NSScanner scannerWithString:self.priceTextfield.text];
    BOOL success = [scanner scanDouble:NULL];
    if (!success) {
        [self showHint:@"请输入有效充值金额"];
        return;
    }
    if (_selectIndex == NSNotFound) {
        [self showHint:@"请选择支付方式"];
        return;
    } else if (_selectIndex == 0) {
        [[AlipaySDK defaultService] payOrder:[self getAlipayOrderString] fromScheme:@"alipaySDK" callback:^(NSDictionary *resultDic) {
            NSInteger resultStatus = [resultDic[@"resultStatus"] integerValue];
            //            ZDPayResultController *resutlVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"payResultVC"];
            
            [self showHint:@"订单支付成功"];
            NSArray *childVCs = self.navigationController.childViewControllers;
            ZDWalletController *vc = childVCs[childVCs.count - 1];
            switch (resultStatus) {
                case 9000:
                    //                    resutlVC.success = YES;
                    [vc refreshData];
                    [self.navigationController popViewControllerAnimated:YES];
                    break;
                case 8000:
                    [self showHint:@"正在处理中"];
                    break;
                case 4000:
                    [self showHint:@"订单支付失败"];
                    break;
                case 6001:
                    [self showHint:@"用户中途取消"];
                    break;
                case 6002:
                    [self showHint:@"网络连接出错"];
                    break;
            }
            //            [self showViewController:resutlVC sender:nil];
        }];
    } else if (_selectIndex == 1) {
        // FIXME 银联待测
        BMRequest *request = [BMRequest requestWithPath:@"unionPay.htm"];
        request.params = @{@"disId": @([BMAccountManager sharedInstance].user.ID), @"txnAmt": self.priceTextfield.text};
        [self showHudWithhint:kDefaultMessage];
        [[BMHttpTool sharedInstance] postWith:request finish:^(BMResponse *response, NSError *error) {
            [self hideHud];
            if (response.status == kResultOK) {
                NSString *tn = response.rawResult[@"unionInfo"][@"tn"];
                [UPPayPlugin startPay:tn mode:@"00" viewController:self delegate:self];
            } else {
                [self showHint:response.msg];
            }
        }];
    }
}

- (void)UPPayPluginResult:(NSString *)result
{
    //    ZDPayResultController *resultVC = [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"payResultVC"];
    if ([@"success" isEqualToString:result]) {
        //        resultVC.success = YES;
        NSArray *childVCs = self.navigationController.childViewControllers;
        ZDWalletController *vc = childVCs[childVCs.count - 2];
        [vc refreshData];
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self showHint:@"充值失败"];
    }
    //    [self showViewController:resultVC sender:nil];
}

- (NSString *)getAlipayOrderString
{
    NSString *price = self.priceTextfield.text;
    
    NSMutableString * orderSpec = [NSMutableString string];
    [orderSpec appendFormat:@"partner=\"%@\"", AliPayPID];
    
    [orderSpec appendFormat:@"&seller_id=\"%@\"", AliPayProductID];
    [orderSpec appendFormat:@"&out_trade_no=\"%@\"", [self generateTradeNO]];
    [orderSpec appendFormat:@"&subject=\"%@\"", @"砼车帮充值金额"];
    [orderSpec appendFormat:@"&total_fee=\"%@\"", [NSString stringWithFormat:@"%@", price]];
    [orderSpec appendFormat:@"&notify_url=\"%@\"", [NSString stringWithFormat:@"%@%@%@%ld.htm", kServerPath, kInterfacePath, AliPayRedirectURL, [BMAccountManager sharedInstance].user.ID]];
    [orderSpec appendFormat:@"&service=\"%@\"",@"mobile.securitypay.pay"];
    [orderSpec appendFormat:@"&payment_type=\"%@\"",@"1"];//1
    [orderSpec appendFormat:@"&_input_charset=\"%@\"",@"utf-8"];//utf-8
    [orderSpec appendFormat:@"&it_b_pay=\"%@\"",@"30m"];//30m
    [orderSpec appendFormat:@"&show_url=\"%@\"",@"m.alipay.com"];//m.alipay.com
    id<DataSigner> signer = CreateRSADataSigner(AliPayPrivateKey);
    NSString *signedString = [signer signString:orderSpec];
    if (signedString) {
        return [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                orderSpec, signedString, @"RSA"];
    } else {
        return nil;
    }
}

- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}

@end
